package cn.code4java.springbok.service;

import cn.code4java.springbok.dto.CouponDirectDTO;
import cn.code4java.springbok.dto.CouponDirectQueryDTO;
import cn.code4java.springbok.dto.MemberCouponCreateDTO;
import cn.code4java.springbok.entity.CouponDirect;
import cn.code4java.springbok.entity.CouponDirectLine;
import cn.code4java.springbok.entity.Member;
import cn.code4java.springbok.mapper.CouponDirectLineMapper;
import cn.code4java.springbok.mapper.CouponDirectMapper;
import cn.code4java.springbok.mapper.MemberMapper;
import cn.code4java.springbok.utils.DateUtils;
import cn.code4java.springbok.vo.CouponDirectLineVO;
import cn.code4java.springbok.vo.CouponDirectVO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CouponDirectServiceImpl
 * @Description: 定向发券服务类
 * @Author zhonghengtech
 * @Date 2024/6/1
 * @Version V1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class CouponDirectServiceImpl extends BaseServiceImpl<CouponDirectMapper, CouponDirect> implements CouponDirectService {

    private MemberCouponService memberCouponService;
    private CouponDirectMapper couponDirectMapper;
    private CouponDirectLineMapper couponDirectLineMapper;
    private MemberMapper memberMapper;

    /**
     * 分页查询定向发券
     *
     * @param couponDirectQueryDTO
     * @return
     */
    @Override
    public Page<CouponDirect> pageCouponDirect(CouponDirectQueryDTO couponDirectQueryDTO) {
        return couponDirectMapper.pageCouponDirect(getPage(), couponDirectQueryDTO);
    }

    /**
     * 根据id查询优惠券
     *
     * @param id
     * @return
     */
    @Override
    public CouponDirectVO selectCouponDirectById(Integer id) {
        CouponDirect couponDirect = couponDirectMapper.selectById(id);
        CouponDirectVO couponDirectVO = BeanUtil.toBean(couponDirect, CouponDirectVO.class);
        List<CouponDirectLineVO> couponDirectLineList = couponDirectLineMapper.selectCouponDirectLine(id);
        couponDirectVO.setCouponDirectLineList(couponDirectLineList);
        return couponDirectVO;
    }

    /**
     * 新增定向发券
     *
     * @param couponDirectDTO
     * @return
     */
    @Override
    @Transactional
    public boolean addCouponDirect(CouponDirectDTO couponDirectDTO) {
        couponDirectDTO.setStatus(0);
        couponDirectMapper.insert(couponDirectDTO);
        if (CollectionUtil.isNotEmpty(couponDirectDTO.getCouponDirectLineList())) {
            couponDirectDTO.getCouponDirectLineList().stream().forEach(couponDirectLine -> {
                couponDirectLine.setCouponDirectId(couponDirectDTO.getCouponDirectId());
                couponDirectLineMapper.insert(couponDirectLine);
            });
        }
        return true;
    }

    /**
     * 修改定向发券
     *
     * @param couponDirectDTO
     * @return
     */
    @Override
    @Transactional
    public boolean updateCouponDirect(CouponDirectDTO couponDirectDTO) {
        couponDirectLineMapper.delete(Wrappers.<CouponDirectLine>lambdaQuery().eq(CouponDirectLine::getCouponDirectId, couponDirectDTO.getCouponDirectId()));
        if (CollectionUtil.isNotEmpty(couponDirectDTO.getCouponDirectLineList())) {
            couponDirectDTO.getCouponDirectLineList().stream().forEach(couponDirectLine -> {
                couponDirectLine.setCouponDirectLineId(couponDirectDTO.getCouponDirectId());
                couponDirectLineMapper.insert(couponDirectLine);
            });
        }
        return updateById(couponDirectDTO);
    }

    /**
     * 删除定向发券
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteCouponDirect(Integer id) {
        couponDirectLineMapper.delete(Wrappers.<CouponDirectLine>lambdaQuery().eq(CouponDirectLine::getCouponDirectId, id));
        return removeById(id);
    }

    /**
     * 发券
     * todo 发券接口较慢，应移入消息队列中
     *
     * @param couponDirectId
     * @return
     */
    @Override
    @Transactional
    public boolean sendCoupon(Integer couponDirectId) {
        // 发券
        CouponDirect couponDirect = couponDirectMapper.selectById(couponDirectId);
        List<CouponDirectLine> couponDirectLines = couponDirectLineMapper.selectList(Wrappers.<CouponDirectLine>lambdaQuery().eq(CouponDirectLine::getCouponDirectId, couponDirectId));
        int sendNum = 0;
        List<Member> members = new ArrayList<>();
        for (CouponDirectLine couponDirectLine : couponDirectLines) {
            String[] sendTargetIds = couponDirect.getSendTargetIds().split(",");
            if (couponDirect.getSendType() == 1) {
                // 按标签
            } else if (couponDirect.getSendType() == 2) {
                // 按手机号
                members = memberMapper.selectList(Wrappers.<Member>lambdaQuery().in(Member::getPhone, ListUtil.toList(sendTargetIds)));
            }
            if (CollectionUtil.isNotEmpty(members)) {
                for (Member member : members) {
                    MemberCouponCreateDTO memberCouponCreateDTO = new MemberCouponCreateDTO();
                    memberCouponCreateDTO.setNum(couponDirectLine.getSendNum());
                    memberCouponCreateDTO.setCouponId(couponDirectLine.getCouponId());
                    memberCouponCreateDTO.setMemberId(member.getMemberId());
                    if (couponDirectLine.getValidityType() == 1) {
                        memberCouponCreateDTO.setStartDate(couponDirectLine.getStartDate());
                        memberCouponCreateDTO.setEndDate(couponDirectLine.getEndDate());
                    } else {
                        memberCouponCreateDTO.setStartDate(DateUtils.localDateToDate(LocalDate.now().plusDays(couponDirectLine.getAfterDayNum())));
                        memberCouponCreateDTO.setEndDate(DateUtils.localDateToDate(LocalDate.now().plusDays(couponDirectLine.getAfterDayNum()).plusDays(couponDirectLine.getValidDayNum())));
                    }
                    memberCouponService.createMemberCoupon(memberCouponCreateDTO);
                    sendNum += couponDirectLine.getSendNum();
                }
            }
        }
        log.info("定向发券成功，{}名用户共发放{}张券", members.size(), sendNum);
        couponDirect.setStatus(2);
        couponDirectMapper.updateById(couponDirect);
        return true;
    }
}
